package org.example.ruoxing_admin_springboot3.service.user;
import jakarta.annotation.Resource;
import org.example.ruoxing_admin_springboot3.dao.SystemResourcesMenuListDao;
import org.example.ruoxing_admin_springboot3.dao.UserRoleRelationDao;
import org.example.ruoxing_admin_springboot3.exceptionHandleUtils.ExceptionHandleUtils;
import org.example.ruoxing_admin_springboot3.httpResponseResult.ResponseResult;
import org.example.ruoxing_admin_springboot3.mapper.SystemResourcesMenuMapper;
import org.example.ruoxing_admin_springboot3.mapper.UserInfoMapper;
import org.example.ruoxing_admin_springboot3.utils.JWTUtils;
import org.example.ruoxing_admin_springboot3.viewmodel.ResourcesMenuTreeBuilder;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class UserResourcesService {
    @Resource
    private SystemResourcesMenuMapper systemResourcesMenuMapper;
    @Resource
    private UserInfoMapper userInfoMapper;
    public ResponseResult<Object> getUserMenuResources(String token) {
        try {
            //解析token
            String userId =  JWTUtils.parseTokenGetUserId(token);
            //通过uerId查询用户拥有的角色
            List<UserRoleRelationDao> roleList =  userInfoMapper.getRoleListByUserId(userId);
            //循环角色查询角色拥有的菜单资源
            List<String> permissionResourcesIdList = new ArrayList<>();
            for (UserRoleRelationDao role : roleList) {
                List<SystemResourcesMenuListDao>  RoleResourcesDaoList = systemResourcesMenuMapper.getSystemResourcesByRoleId(role.getRoleId());
                for (SystemResourcesMenuListDao roleResources : RoleResourcesDaoList) {
                    //如果已经存在，则不添加
                    if (permissionResourcesIdList.contains(roleResources.getResourcesId())) {
                        continue;
                    }
                    permissionResourcesIdList.add(roleResources.getResourcesId());
                }
            }
            //查询所有菜单资源
            List<SystemResourcesMenuListDao> systemMenuResourcesDaoList = systemResourcesMenuMapper.getAllSystemResources();
            //转为符合权限的菜单资源树
            List<SystemResourcesMenuListDao> systemResourcesMenuList = ResourcesMenuTreeBuilder.buildPermissionsMenuTree(systemMenuResourcesDaoList,permissionResourcesIdList);
            return  ResponseResult.SUCCESS(systemResourcesMenuList);
        }catch (Exception e){
            ExceptionHandleUtils.reportException(e, "获取用户菜单资源失败!");
            return ResponseResult.ERROR();
        }
    }
}
